# 宠物档案建立
from PetNetadmin.serializers import PetMessageSerializer
from admincharge.models import PetMessage
from utils.imageupload import ImageUpload
from admincharge.utils.jwt import MyJWTAuthentication
import os
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view

# 所有宠物基本信息
class NetShopPetNetMessageView(APIView):
    def get(self, request):
        # 获取当前登录用户的账号
        # print(request.GET.get('username'))
        username = request.GET.get('username')
        pet_message_all_list = PetMessage.objects.filter(apply_account=username)
        serializer = PetMessageSerializer(instance=pet_message_all_list, many=True)
        result = {
            'data': serializer.data,
            'code': 2000,
            'msg': '获取成功'
        }
        return Response(result)
    def post(self,request):
        # 新增建档档案
        data = request.data
        print('data',data)
        serializer = PetMessageSerializer(data=data, partial=True)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            result = {
                'code': 2000,
                'msg': '上传保存成功'
            }
            return Response(status=status.HTTP_200_OK, data=result)
        return Response({"msg": '出了点问题噢!!!'}, status=status.HTTP_400_BAD_REQUEST)

class UploadNetShopPetImageView(APIView):
    def post(self, request):
        result = ImageUpload(request, 'images')
        print(result)
        if result['code'] == 2000:
            return Response(data=result['img'])
        else:
            return Response('没有上传成功')

# 删除一份数据
@api_view(['POST'])
def deleteOnePetmsg(request, id):
    try:
        petMsg = PetMessage.objects.get(pk=id)
        imagefile = PetMessage.objects.get(pk=id).imagesurl
        print(imagefile)
        petMsg.delete()
        imagefile = imagefile.split(':8000/')[1]
        print(imagefile)
        if os.path.exists(imagefile):
            os.remove(imagefile)
        result = {
            'code': 2000,
            'msg': '删除成功'
        }
        return Response(data=result, status=status.HTTP_200_OK)
    except PetMessage.DoesNotExist:
        return Response({"msg": '当前没有该记录可以删除'}, status=status.HTTP_404_NOT_FOUND)